package com.coder.rental.controller;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.coder.rental.entity.AutoInfo;
import com.coder.rental.service.IAutoInfoService;
import com.coder.rental.utils.Result;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tuboyuan
 * @since 2025-09-04
 */
@RestController
@RequestMapping("/rental/autoInfo")
public class AutoInfoController {
    @Resource
    private IAutoInfoService autoInfoService;
    @Value("${auto.info.maintain-mileage}")
    private Integer maintainMileage;
    /**
     * 分页搜索车辆信息
     * @param page 页码
     * @param size 每页大小
     * @param autoInfo 搜索条件
     * @return 分页搜索结果
     */
    @PostMapping("/{page}/{size}")
    public Result search(@PathVariable int page, @PathVariable int size, @RequestBody AutoInfo autoInfo){
        Page<AutoInfo> page1=new Page<>(page,size);
        return  Result.success(autoInfoService.searchByPage(page1,autoInfo));
    }

    /**
     * 保存车辆信息
     * 根据里程数计算并设置应保次数和实保次数
     * @param autoInfo 车辆信息
     * @return 保存结果
     */
    @PostMapping
    public Result save(@RequestBody AutoInfo autoInfo){
        //设置一下应保次数和实保次数
        int i=autoInfo.getMileage()/maintainMileage;
        autoInfo.setExpectedNum(i);
        autoInfo.setActualNum(i);
        return autoInfoService.save(autoInfo)?Result.success():Result.fail();
    }

    /**
     * 更新车辆信息
     * 根据里程数重新计算并设置应保次数和实保次数
     * @param autoInfo 车辆信息
     * @return 更新结果
     */
    @PutMapping
    public Result update(@RequestBody AutoInfo autoInfo){
        int i=autoInfo.getMileage()/maintainMileage;
        autoInfo.setExpectedNum(i);
        autoInfo.setActualNum(i);
        return autoInfoService.updateById(autoInfo)?Result.success():Result.fail();
    }

    /**
     * 删除车辆信息
     * @param ids 要删除的车辆ID列表，多个ID用逗号分隔
     * @return 删除结果
     */
    @DeleteMapping("/{ids}")
    public Result delete(@PathVariable String ids){
        return Result.success(autoInfoService.delete(ids));
    }

    /**
     * 检查车辆是否存在
     * @param autoInfo 包含车牌号的车辆信息
     * @return 存在返回"have"，不存在返回"none"
     */
    @PostMapping("exist")
    public Result exist(@RequestBody AutoInfo autoInfo){
        AutoInfo info = autoInfoService.selectByAutoNum(autoInfo.getAutoNum());
        return ObjectUtil.isNotEmpty(info) ?
                Result.success().setMessage("have"):Result.success().setMessage("none");
    }

    @GetMapping("toBeMaintain")
    public Result toBeMaintain(){
        return Result.success(autoInfoService.toBeMaintain());
    }

}
